// 状态提升
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
const root = ReactDOM.createRoot(document.getElementById("root"));
class Square extends React.Component {
  render() {
    return (
      <button
				className="square"
				onClick={() => this.props.onClick()}
			>
        {this.props.value}
      </button>
    );
  }
}

class Board extends React.Component {
	constructor(props) {
	    super(props);
	    this.state = {
	      squares: Array(9).fill(null),
	    };
	}
	/* 不可变性在 React 中非常重要
	 * 两种改变数据的方式：
	 * 	1.直接修改变量的值：player.score = 2
	 * 	2.使用新的数据替换旧数据：let newPlayer = {...player, score: 2}
	 * 		或者 let newPlayer = Object.assign({}, player, {score: 2})
	 * 不直接修改（或改变底层数据）的好处
	 * 	1.简化复杂的功能
	 * 	2.跟踪数据的改变
	 * 	3.确定在 React 中何时重新渲染
	 */
	handleClick(i) {
		// 创建 square 数组的副本
	  const squares = this.state.squares.slice();
	  squares[i] = 'X';
	  this.setState({squares: squares});
	}
		
  renderSquare(i) {
     return <Square 
							value={this.state.squares[i]}
							onClick={() => this.handleClick(i)}
						/>;
  }

  render() {
    const status = 'Next player: X';

    return (
      <div>
        <div className="status">{status}</div>
        <div className="board-row">
          {this.renderSquare(0)}
          {this.renderSquare(1)}
          {this.renderSquare(2)}
        </div>
        <div className="board-row">
          {this.renderSquare(3)}
          {this.renderSquare(4)}
          {this.renderSquare(5)}
        </div>
        <div className="board-row">
          {this.renderSquare(6)}
          {this.renderSquare(7)}
          {this.renderSquare(8)}
        </div>
      </div>
    );
  }
}

class Game extends React.Component {
  render() {
    return (
      <div className="game">
        <div className="game-board">
          <Board />
        </div>
        <div className="game-info">
          <div>{/* status */}</div>
          <ol>{/* TODO */}</ol>
        </div>
      </div>
    );
  }
}

root.render(<Game />);
